package com.jdew.thkj.activity;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Looper;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.webkit.CookieManager;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.baichuan.android.trade.AlibcTrade;
import com.alibaba.baichuan.android.trade.callback.AlibcTradeCallback;
import com.alibaba.baichuan.android.trade.model.AlibcShowParams;
import com.alibaba.baichuan.android.trade.model.OpenType;
import com.alibaba.baichuan.android.trade.page.AlibcPage;
import com.alibaba.baichuan.trade.biz.context.AlibcTradeResult;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.JsonObject;
import com.jdew.thkj.R;
import com.jdew.thkj.base.BaseActivity;
import com.jdew.thkj.bean.GuideBean;
import com.jdew.thkj.bean.PidBean;
import com.jdew.thkj.manager.AppConfig;
import com.jdew.thkj.network.RetrofitManager;
import com.jdew.thkj.network.api.RequestApi;
import com.jdew.thkj.utils.MD5Utils;
import com.jdew.thkj.utils.RegexValidateUtils;
import com.jdew.thkj.utils.ToastUtils;
import com.jdew.thkj.view.NetworkProgressDialog;

import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by yangyang on 2017/9/19.
 */

public class WebViewActivity extends BaseActivity {
    @Bind(R.id.webView)
    WebView webView;
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.title)
    TextView title;
    private String weburl;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private int type = 0;
    private String tb_token;
    private String cookie;
    private String guideId;
    private String ip;
    private String pid;
    private String code;
    private String biaoti;

    @Override
    public int bindLayout() {
        return R.layout.activity_webview;
    }

    @Override
    public void initView(View view) {
        weburl = getIntent().getStringExtra("url");
        sp = getSharedPreferences("user", MODE_PRIVATE);
        editor = sp.edit();
        biaoti = getIntent().getStringExtra("title");
        title.setText(biaoti);
        back.setVisibility(View.VISIBLE);
        back.setOnClickListener(this);
        //获取wifi服务
        WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        //判断wifi是否开启
        if (!wifiManager.isWifiEnabled()) {
            ip = getLocalIpAddress();
        } else {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            ip = intToIp(ipAddress);
        }
        initWebView();
    }

    private String intToIp(int i) {

        return (i & 0xFF) + "." +
                ((i >> 8) & 0xFF) + "." +
                ((i >> 16) & 0xFF) + "." +
                (i >> 24 & 0xFF);
    }

    //获取本地IP
    @SuppressLint("LongLogTag")
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf
                        .getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
            Log.e("WifiPreference IpAddress", ex.toString());
        }


        return null;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back: {
                finish();
            }
            break;
        }
    }

    private void initWebView() {
        WebSettings webSettings = webView.getSettings();
        webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);
        webSettings.setSupportZoom(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setDatabaseEnabled(true);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new InJavaScriptLocalObj(), "java_obj");
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        //设置Web视图
        webView.setWebViewClient(new CustomWebViewClient());
        webView.setWebChromeClient(new WebChromeClient());
        webView.loadUrl(weburl);
    }

    public void postToken(final String token) {
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).AddToken(token, sp.getString("userName", "")).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                NetworkProgressDialog.ProgressDialogBarView.dismiss();
            }

            @Override
            public void onError(Throwable e) {
                NetworkProgressDialog.ProgressDialogBarView.dismiss();
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    finish();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    class CustomWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            if (url.contains("?code=")) {
                if (null == code) {
                    code = url.substring(url.indexOf("?code=") + 6, url.indexOf("&"));
                    getUrl("https://oauth.taobao.com/token");
                }
            }
            if (type == 1) {
                view.loadUrl("javascript:window.java_obj.getSource('<head>'+" +
                        "document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            }
            if (type == 2) {
                CookieManager cookieManager = CookieManager.getInstance();
                cookie = cookieManager.getCookie(url);
                String[] map = cookie.split(";");
                for (int i = 0; i < map.length; i++) {
                    if (map[i].startsWith(" _tb_token_") || map[i].startsWith("_tb_token_")) {
                        tb_token = map[i].split("=")[1];
                    }
                }
//                guideAdd();
            }
        }

        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }
    }

    final class InJavaScriptLocalObj {
        @JavascriptInterface
        public void getSource(String html) {
            JSONObject jsonObject = JSONObject.parseObject(Html.fromHtml(html).toString());
            if (null != jsonObject && null != jsonObject.getString("access_token")) {
                String token = jsonObject.getString("access_token");
                editor.putString("token", token);
                editor.apply();
                postToken(token);
            }
        }
    }

    public void guideAdd() {
        Date nowTime = new Date(System.currentTimeMillis());
        String time = nowTime.getTime() + "";
        String url = "http://pub.alimama.com/common/site/generalize/guideAdd.json";
        Request.Builder builder = new Request.Builder().url(url);
        builder.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        builder.addHeader("Referer", "http://pub.alimama.com/myunion.htm?spm=a219t.7900221/10.1998910286.da889112");
        builder.addHeader("Cookie", cookie);
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build(); //设置各种超时时间
        RequestBody requestBodyPost = new FormBody.Builder()
                .add("name", "测试微信导购" + System.currentTimeMillis())
                .add("categoryId", "14")
                .add("account1", "huiwan00000")
                .add("t", time)
                .add("pvid", "")
                .add("_tb_token_", tb_token)
                .build();
        builder.post(requestBodyPost);
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                try {
                    JSONObject json = JSONObject.parseObject(result);
                    if (null != json.getBoolean("ok") && json.getBoolean("ok")) {
                        getGuideId();
                    }
                } catch (Exception e) {
                    finish();
                    Looper.loop();
                }
                Looper.loop();
            }
        });
    }

    public void getGuideId() {
        final String url = "http://pub.alimama.com/common/site/generalize/guideList.json?t=1509970114486&pvid=&_tb_token_=" + tb_token + "&_input_charset=utf-8";
        Request.Builder builder = new Request.Builder().url(url);
        builder.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        builder.addHeader("Referer", "http://pub.alimama.com/myunion.htm?spm=a219t.7900221/10.1998910286.da889112");
        builder.addHeader("Cookie", cookie);
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                GuideBean bean = JSONObject.parseObject(result, GuideBean.class);
                guideId = bean.getData().getGuideList().get(0).getGuideID() + "";
                Creat();
                Looper.loop();
            }
        });
    }

    public void Creat() {
        Date nowTime = new Date(System.currentTimeMillis());
        String time = nowTime.getTime() + "";
        String url = "http://pub.alimama.com/common/adzone/selfAdzoneCreate.json";
        Request.Builder builder = new Request.Builder().url(url);
        builder.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        builder.addHeader("Referer", "http://pub.alimama.com/promo/search/index.htm?spm=a219t.7664554.1998457203.dfb");
        builder.addHeader("Cookie", cookie);
        builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0; SE 2.X MetaSr 1.0) like Gecko");
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build(); //设置各种超时时间
        RequestBody requestBodyPost = new FormBody.Builder()
                .add("tag", "29")
                .add("gcid", "8")
                .add("siteid", guideId)
                .add("selectact", "add")
                .add("t", time)
                .add("newadzonename", "测试微信导购" + System.currentTimeMillis())
                .add("_tb_token_", tb_token)
                .add("pvid", "10_" + ip + "_494_" + time)
                .build();
        builder.post(requestBodyPost);
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                JSONObject json = JSONObject.parseObject(result);
                if (json.getBoolean("ok")) {
                    getPid();
                }
                Looper.loop();
            }
        });
    }

    public void getPid() {
        Date nowTime = new Date(System.currentTimeMillis());
        String time = nowTime.getTime() + "";
        final String url = "http://pub.alimama.com/common/adzone/adzoneManage.json?tab=3&toPage=1&perPageSize=40&gcid=8&t=" + time + "&pvid=" + "60_" + ip + "_533_" + time + "&_tb_token_=" + tb_token + "&_input_charset=utf-8";
        Request.Builder builder = new Request.Builder().url(url);
        builder.addHeader("Accept", "application/json, text/javascript, */*; q=0.01");
        builder.addHeader("X-Requested-With", "XMLHttpRequest");
        builder.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        builder.addHeader("Referer", "http://pub.alimama.com/promo/search/index.htm?spm=a219t.7664554.1998457203.dfb");
        builder.addHeader("Cookie", cookie);
        builder.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0; SE 2.X MetaSr 1.0) like Gecko");
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .build();
        Request request = builder.build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                PidBean bean = JSONObject.parseObject(result, PidBean.class);
                List<PidBean.DataBean.PagelistBean> list = bean.getData().getPagelist();
                pid = list.get(list.size() - 1).getAdzonePid();
                postMpid();
                Looper.loop();
            }
        });
    }

    public void postMpid() {
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).AddMPid(pid, sp.getString("userName", "")).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
                NetworkProgressDialog.ProgressDialogBarView.dismiss();
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                if (json.getString("code").equals("1")) {
                    editor.putString("mpid", pid);
                    editor.putString("Adzoneid", pid.split("_")[3]);
                    editor.putString("Siteid", pid.split("_")[2]);
                    editor.apply();
                    finish();
                }
            }
        });
    }

    public void getUrl(String url) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        RequestBody requestBodyPost = new FormBody.Builder()
                .add("client_id", "24895091")
                .add("client_secret", "1c90653bd59a558a0a8c465c6f58eff4")
                .add("grant_type", "authorization_code")
                .add("code", code)
                .add("redirect_uri", "http://www.taohuikeji.com")
                .add("view", "wap")
                .build();
        final Request request = new Request.Builder()
                .url(url)
                .post(requestBodyPost)
                .build();
        Call call = mOkHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Looper.prepare();
                String result = response.body().string();
                JSONObject json = JSONObject.parseObject(result);
                String access_token = json.getString("access_token");
                SetPublisher(access_token);
                Looper.loop();
            }
        });
    }

    public void SetPublisher(String token) {
        String timesamp = RegexValidateUtils.getTime13();
        String numsamp = RegexValidateUtils.getRandom10();
        RetrofitManager.getInstance(AppConfig.BASE_URL)
                .createReq(RequestApi.class).SetPublisher(token, sp.getString("userId", ""), RegexValidateUtils.getUniquePsuedoID(), timesamp, numsamp, MD5Utils.getMD5(RegexValidateUtils.ASCIISort(timesamp + numsamp + RegexValidateUtils.getUniquePsuedoID() + sp.getString("SignToken", "") + "Token" + token + "UserId" + sp.getString("userId", ""))).toUpperCase()).observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe(new Subscriber<JSONObject>() {
            @Override
            public void onCompleted() {
            }

            @Override
            public void onError(Throwable e) {
            }

            @Override
            public void onNext(JSONObject json) {
                ToastUtils.getInstance(WebViewActivity.this).showMessage(json.getString("message"));
                startActivity(MainActivity.class);
            }
        });
    }
}
